# -*- encoding:utf-8 -*-
#
from demo import app, manager
from demo.hooks import load_db, clear_db
from demo.utils.funs import *
import os

@manager.option('-m', dest='model_name', default='')
@manager.option('-t', dest='table_type', default='1')
def model(model_name, table_type):
    sql_file = os.path.join(os.path.dirname(__file__), '../sqls/' + model_name + '.sql')
    with open(sql_file, 'r') as f:
        sql = f.readlines()
    sql = ''.join(sql)
    db = load_db()

    if table_type == 'build':
        db.update(sql)
    elif table_type == 'rebuild':
        db.update('drop table ' + model_name)
        db.update(sql)
    elif table_type == 'source only':
        pass
    else:
        return


    # 获取表信息
    table_info = db.get_one('show table status where Name="%s"' % (model_name))
    table_name = table_info['Comment']
    model_cls = to_hump(model_name)

    # 获取字段信息
    table_info = db.get_all('show full fields from ' + model_name)
    cols = {}
    for item in table_info:
        if item['Field'] == 'id':
            continue
        cols[item['Field']] = {}
        cols[item['Field']]['name'] = item['Comment'] or item['Field']
        col_type = item['Type']
        if col_type.find('int') == 0 or \
            col_type.find('float') == 0:
            cols[item['Field']]['type'] = 'num'
        else:
            cols[item['Field']]['type'] = 'string'

    cols_str = ''
    for k, v in cols.items():
        cols_str += '"%s": {"name": "%s", "type": "%s"}, ' % (k, v['name'], v['type'])
    cols_str = cols_str[:-2]

    # 生成model
    model = '''# -*- encoding:utf-8 -*-
from .base_model import BaseModel

class %s(BaseModel):
    cols = {%s}
    model_name = "%s"
''' % (model_cls, cols_str, table_name)

    with open(os.path.join(os.path.dirname(__file__), '../models/' + model_name + '.py'), 'w') as f:
        f.write(model)

    # 生成controller
    controller = '''# -*- encoding:utf-8 -*-
from demo import app
from demo.utils.funs import *
from . import render_template, route
from demo.models.<<<model>>> import <<<model_cls>>>
from flask import g, request, redirect, url_for, flash

@route('/<<<model>>>/list')
@login_required
@check_access
def <<<model>>>_list():

    page = get_params('p', default=1, type=int)
    size = 30
    condition = {}
    <<<model>>>_obj = <<<model_cls>>>()
    for k in <<<model>>>_obj.cols:
        v = request.args.get(k)
        if v:
            condition[k] = [v, '=']

    data, page = <<<model>>>_obj.find_pageble(condition, page, size)
    return render_template('/<<<model>>>/list.html', list=data, page=page, req=request.args)



@route('/<<<model>>>/edit', methods=['GET', 'POST'])
@login_required
@check_access
def <<<model>>>_edit():

    id = get_params('id', default=None)

    <<<model>>>_obj = <<<model_cls>>>()
    if request.method == 'GET':
        # to new
        if not id:
            return render_template('/<<<model>>>/edit.html', <<<model>>>={}, req=request.args)

        # to edit
        data = <<<model>>>_obj.find(id)
        return render_template('/<<<model>>>/edit.html', <<<model>>>=data, req=request.args)

    # save
    try:'''

    for k in cols:
        controller += '''
        %s = get_params('%s', required='缺少%s参数')''' % (k, k, cols[k]['name'])

    controller += '''
    except Exception as e:
        return show_error(str(e))

    data = {'''
    for k in cols:
        controller += '"%s": %s, ' % (k, k)
    controller = controller[:-2]
    controller += '''}
    if id:
        res = <<<model>>>_obj.save(data, id)
        if res:
            flash('保存成功')
    else:
        res = <<<model>>>_obj.save(data)
        if not res:
            return show_error('用户已存在')
        else:
            flash('保存成功')

    return redirect(request.headers.get('referer'))



@route('/<<<model>>>/del', methods=['POST'])
@login_required
@check_access
def <<<model>>>_del():

    id = get_params('id', required='缺少必要参数')

    <<<model>>>_obj = <<<model_cls>>>()
    if <<<model>>>_obj.delete(id):
        flash('删除成功')
    else:
        return show_error('删除失败，请联系管理员')
    return redirect(request.headers.get('referer'))

'''
    controller = controller.replace('<<<model>>>', model_name)
    controller = controller.replace('<<<model_cls>>>', model_cls)
    with open(os.path.join(os.path.dirname(__file__), '../controllers/admin/' + model_name + '.py'), 'w') as f:
        f.write(controller)


    # 生成模板
    tmp_path = os.path.join(os.path.dirname(__file__), '../templates/admin/' + model_name)
    if not os.path.exists(tmp_path):
        os.makedirs(tmp_path)

    template = '''
{% extends "admin/common/layout.html" %}
{% block active %}<<<model>>>{% endblock %}
{% block body %}
<h2><<<table_name>>>管理</h2>
{% include "admin/common/flash.html" %}
{% include "admin/<<<model>>>/nav.html" %}
<style type="text/css">
form.search {margin-bottom: 15px;}
form .group_offset {margin-right: 20px; margin-top: 5px}
form .label_offset {margin-right: 10px}
</style>
<form class="form-inline search" role="form" >'''
    for k, v in cols.items():
        template += '''
    <div class="form-group group_offset" >
        <label class="control-label label_offset">%s</label>
        <input type="text" class="form-control" id="%s" name="%s" placeholder="检索%s" value="{{ req.%s or '' }}" >
    </div>''' % (v['name'], k, k, v['name'], k)

    template += '''
    <div class="form-group group_offset" role="toolbar">
        <div class="btn-group" role="group">
            <button type="submit" class="btn btn-default">检索</button>
        </div>
    </div>
</form>
<table class="table table-striped">
<thead>
    <tr>
        <th>ID</th>
        <th></th>
'''
    template = template.replace('<<<table_name>>>', table_name)
    for k, v in cols.items():
        template += '<th>%s</th>' % (v['name'])

    template += '''
    </tr>
</thead>
<tbody>
    {% for item in list %}
    <tr>
        <td>{{ item.id }}</td>
        <td>
            <a href="{{ url_for('admin.<<<model>>>_edit', id=item.id) }}">
                <span class="fa fa-pencil glyphicon glyphicon-pencil"></span>
            </a>
            <form class="icon" method="POST" action="{{ url_for('admin.<<<model>>>_del') }}" id='form_{{ item.id }}' style='display: inline;'>
                <input id="id" name="id" type="hidden" value="{{ item.id }}">
                <a href="#" id='btn_del' data-id='{{ item.id }}'>
                    <span class="fa fa-trash glyphicon glyphicon-trash"></span>
                </a>
            </form>
        </td>
'''
    for k in cols:
        template += '<td>{{ item.%s }}</td>' % (k)

    template += '''
    </tr>
    {% endfor %}
</tbody>
</table>
{% include "admin/common/page.html" %}
<script>
$(function(){
    $('#btn_del').click(function() {
        if (confirm('是否确定要删除该记录？')) {
            var id = $(this).data('id')
            $('#form_' + id).submit()
        }
    })
})
</script>
{% endblock %}
'''
    template = template.replace('<<<model>>>', model_name)
    with open(os.path.join(tmp_path, 'list.html'), 'w') as f:
        f.write(template)

    template = '''
{% extends "admin/common/layout.html" %}
{% block active %}<<<model>>>{% endblock %}
{% block body %}
<h2><<<table_name>>>管理</h2>
{% include "admin/common/flash.html" %}
{% include "admin/<<<model>>>/nav.html" %}
<form class="form-horizontal" role="form" method="POST">'''
    template = template.replace('<<<table_name>>>', table_name)

    form_item = '''
    <div class="form-group">
        <label for="%s" class="col-sm-2 control-label">%s</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="%s" name="%s" placeholder="请输入%s" value="{{ <<<model>>>.%s }}">
        </div>
    </div>
'''
    for k, v in cols.items():
        template += form_item % (k, v['name'], k, k, v['name'], k)

    template += '''
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10" role="toolbar" aria-label="...">
            <div class="btn-group" role="group">
                <button type="submit" class="btn btn-default">保存</button>
            </div>
        </div>
    </div>
</form>
{% endblock %}
'''
    template = template.replace('<<<model>>>', model_name)
    with open(os.path.join(tmp_path, 'edit.html'), 'w') as f:
        f.write(template)

    template = '''
<ul class="nav nav-tabs" style='margin: 25px 0px;' >
    <li role="presentation"><a href="{{ url_for('admin.<<<model>>>_list') }}">列表</a></li>
    <li role="presentation"><a href="{{ url_for('admin.<<<model>>>_edit') }}">新建·编辑</a></li>
</ul>
<script>
$('ul.nav-tabs li a').each(function(i, item) {
    if (item.href == window.location.protocol + '//' + window.location.host + window.location.pathname) {
        $(item).parent('li').addClass('active')
    }
})
</script>
'''
    template = template.replace('<<<model>>>', model_name)
    with open(os.path.join(tmp_path, 'nav.html'), 'w') as f:
        f.write(template)

    nav = '''
{%% if check_access(url_for("admin.%s_list")) %%}
<li data-cat='%s'><a href="{{ url_for("admin.%s_list") }}">%s管理</a></li>
{%% endif %%}''' % (model_name, model_name, model_name, table_name)
    with open(os.path.join(tmp_path, '../common/nav.html'), 'a') as f:
        f.write(nav)

    clear_db()


